<?php

/**
 *      [品牌空间] (C)2001-2010 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: common.func.php 5756 2011-10-28 05:29:05Z menglingmin $
 */

if(!defined('IN_BRAND')) {
	exit('Access Denied');
}

function lang($file, $langvar = null, $vars = array()) {
	global $_G, $lang;

	if (empty($langvar)) {
		$return = isset($lang[$file]) ? $lang[$file] : ($file ? $file : '');
	} else {
		$key = str_replace('/', '_', $file);
		if(!isset($_G['lang'][$key])) {
			include B_ROOT.'language/'.$file.'.php';
			$_G['lang'][$key] = $advlang;
		}
		$return = isset($_G['lang'][$key][$langvar]) ? $_G['lang'][$key][$langvar] : ($langvar === null ? $file : '');
	}

	if($vars && is_array($vars)) {
		$searchs = $replaces = array();
		foreach($vars as $k => $v) {
			$searchs[] = '{'.$k.'}';
			$replaces[] = $v;
		}
		$return = str_replace($searchs, $replaces, $return);
	}

	return $return;
}

function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$newkey = addslashes(strip_tags($key));
			if($newkey != $key) {
				unset($string[$key]);
			}
			$string[$newkey] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function parseparameter($param) {
	global $_G;

	$paramarr = array();

	$sarr = explode('/', $param);
	if(empty($sarr)) return $paramarr;
	if(is_numeric($sarr[0])) $sarr = array_merge(array('uid'), $sarr);
	if(count($sarr)%2 != 0) $sarr = array_slice($sarr, 0, -1);
	for($i=0; $i<count($sarr); $i=$i+2) {
		if(!empty($sarr[$i+1])) $paramarr[$sarr[$i]] = str_replace(array('/'), '', rawurldecode($sarr[$i+1]));
	}
	if(!empty($paramarr['extra']) && $paramarr['extra']) {
		$paramarr['extra'] = unserialize(stripslashes($paramarr['extra']));
		$paramarr['extra']['thumbwidth'] = intval($paramarr['extra']['thumbwidth']);
		$paramarr['extra']['thumbheight'] = intval($paramarr['extra']['thumbheight']);
	}
	return $paramarr;
}

function arraytostring($array, $dot='/', $dot2='/') {
	$result = $comma = '';
	foreach ($array as $key => $value) {
		$value = trim($value);
		if($value != '') {
			$result .= $comma.$key.$dot.rawurlencode($value);
			$comma = $dot2;
		}
	}
	return $result;
}

//将数组加上单引号,并整理成串
function simplode($sarr, $comma=',') {
	return '\''.implode('\''.$comma.'\'', $sarr).'\'';
}

function gethtmlfile($parray) {

	$htmlarr = array();
	$dirarr = array();
	$id = 0;

	if(empty($parray['page'])) {
		unset($parray['page']);
	} elseif($parray['page'] < 2) {
		unset($parray['page']);
	}
	if(!empty($parray['uid'])) {
		$id = $parray['uid'];
		if(!empty($parray['action'])) {
			if($parray['action'] == 'space' || $parray['action'] == 'spacelist') {
				unset($parray['action']);
			} elseif ($parray['action'] == 'viewspace') {
				unset($parray['action']);
			}
		}
	} elseif(!empty($parray['itemid'])) {
		$id = $parray['itemid'];
	} elseif(!empty($parray['tid'])) {
		$id = $parray['tid'];
	} elseif(!empty($parray['tagid'])) {
		$id = $parray['tagid'];
	} elseif(!empty($parray['catid'])) {
		$id = $parray['catid'];
	} elseif(!empty($parray['fid'])) {
		$id = $parray['fid'];
	}

	$htmlfilename = str_replace(array('action-', 'uid-', 'itemid-'), array('', '', ''), arraytostring($parray, '-'));
	if(!empty($id)) {
		$idvalue = ($id>9)?substr($id, -2, 2):$id;
		$thedir = $idvalue;
		if(!empty($parray['action'])) {
			if($parray['action'] == 'viewnews') {
				$htmlfilename = "n-{$id}";
				if(!empty($parray['page'])) $htmlfilename .= '-'.$parray['page'];
			} elseif($parray['action'] == 'viewthread') {
				$htmlfilename = "t-{$id}";
			}
		}
	}

	if(is_dir(H_DIR) || (!is_dir(H_DIR) && @mkdir(H_DIR))) {
		if(empty($id)) {
			$htmlarr['path'] = H_DIR.'/'.$htmlfilename.'.html';
			$htmlarr['url'] = H_URL.'/'.$htmlfilename.'.html';
		} else {
			$htmldir = H_DIR.'/'.$thedir;
			if(is_dir($htmldir) || (!is_dir($htmldir) && @mkdir($htmldir))) {
				$htmlarr['path'] = H_DIR.'/'.$thedir.'/'.$htmlfilename.'.html';
				$htmlarr['url'] = H_URL.'/'.$thedir.'/'.$htmlfilename.'.html';
			} else {
				$htmlarr['path'] = H_DIR.'/'.$htmlfilename.'.html';
				$htmlarr['url'] = H_URL.'/'.$htmlfilename.'.html';
			}
		}
	} else {
		$htmlarr['path'] = $htmlfilename.'.html';
		$htmlarr['url'] = $htmlfilename.'.html';
	}

	return $htmlarr;
}

function ob_out() {
	global $_G, $_SGLOBAL, $_SC;

	$_SGLOBAL['content'] = ob_get_contents();
	$preg_searchs = $preg_replaces = $str_searchs = $str_replaces = array();

	if($_G['setting']['urltype'] != 4 && $_G['setting']['urltype'] != 5) {
		$preg_searchs[] = "@\"(".B_URL.")?store\.php\?id=(\d+)(&action=(\w+)(&xid=(\d+))?)?\"@is";
		$preg_replaces[] = '"'.B_URL.'store-\\2-\\4-\\6S-H-O-P-E-N-D.html"';
		$preg_searchs[] = "@\"(".B_URL.")?street\.php\?catid=(\d+)(&tagid=(\d+))?\"@is";
		$preg_replaces[] = '"'.B_URL.'street-\\2-\\4T-A-G-E-N-D.html"';
		$str_searchs[] = '--S-H-O-P-E-N-D';
		$str_replaces[] = '';
		$str_searchs[] = '-S-H-O-P-E-N-D';
		$str_replaces[] = '';
		$str_searchs[] = 'S-H-O-P-E-N-D';
		$str_replaces[] = '';
		$str_searchs[] = '-T-A-G-E-N-D';
		$str_replaces[] = '';
		$str_searchs[] = 'T-A-G-E-N-D';
		$str_replaces[] = '';
	}

	if($preg_searchs) {
		$_SGLOBAL['content'] = preg_replace($preg_searchs, $preg_replaces, $_SGLOBAL['content']);
	}
	if($str_searchs) {
		$_SGLOBAL['content'] = trim(str_replace($str_searchs, $str_replaces, $_SGLOBAL['content']));
	}

	obclean();
	if(!$_G['inajax']) {
		if($_G['setting']['headercharset']) {
			@header('Content-Type: text/html; charset='.$_G['charset']);
		}
		echo $_SGLOBAL['content'];
		if(D_BUG && !defined('CREATEHTML')) {
			@include_once(B_ROOT.'./source/include/debug.inc.php');
		}
	}
}

function sgmdate($timestamp, $dateformat='', $format=0) {
	global $_G, $_SGLOBAL, $lang;

	if(empty($dateformat)) {
		$dateformat = 'Y-m-d H:i:s';
	}

	if(empty($timestamp)) {
		$timestamp = $_G['timestamp'];
	}

	$result = '';
	if($format) {
		$time = $_G['timestamp'] - $timestamp;
		if($time > 24*3600) {
			$result = gmdate($dateformat, $timestamp + $_G['setting']['timeoffset'] * 3600);
		} elseif ($time > 3600) {
			$result = intval($time/3600).$lang['hour'].$lang['before'];
		} elseif ($time > 60) {
			$result = intval($time/60).$lang['minute'].$lang['before'];
		} elseif ($time > 0) {
			$result = $time.$lang['second'].$lang['before'];
		} else {
			$result = $lang['now'];
		}
	} else {
		$result = gmdate($dateformat, $timestamp + $_G['setting']['timeoffset'] * 3600);
	}
	return $result;
}

function authcode($string, $operation, $key = '', $expiry = 0) {
	global $_G, $_SGLOBAL;

	$ckey_length = 4;	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥

	$key = md5($key ? $key : $_G['authkey']);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

/**
* PHP数组转换成代码
* @param $array	- 数组
* @param $level	- 缩进用几个制表符
* @return 返回数组的文本字符串
*/
function arrayeval($array, $level = 0) {
	if(!is_array($array)) {
		return "'".$array."'";
	}
	//note use defined function to export array
	if(is_array($array) && function_exists('var_export')) {
		return var_export($array, true);
	}

	$space = '';
	for($i = 0; $i <= $level; $i++) {
		$space .= "\t";
	}
	$evaluate = "Array\n$space(\n";
	$comma = $space;
	if(is_array($array)) {
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
			$val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n$space";
		}
	}
	$evaluate .= "\n$space)";
	return $evaluate;
}

function sclearcookie() {
	ssetcookie('sid', '', -86400 * 365);
	ssetcookie('auth', '', -86400 * 365);
	ssetcookie('sauth', '', -86400 * 365);
}

function ssetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
	global $_G;

	$config = $_G['config']['cookie'];

	$_G['cookie'][$var] = $value;
	$var = ($prefix ? $config['cookiepre'] : '').$var;
	$_COOKIE[$var] = $value;

	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}

	$life = $life > 0 ? $_G['timestamp'] + $life : ($life < 0 ? $_G['timestamp'] - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
	}
}

/**
 * 连接数据库
 */
function dbconnect($mode=0) {
	global $_G, $_SGLOBAL, $_SC;

	$__SC['db'][1] = $_SC;
	if(empty($_G['db'])) {
		include_once(B_ROOT.'./source/class/db.class.php');
		$_G['db'] = DB::object();
		$_G['db']->set_config($__SC['db']);
		$_G['db']->connect();
	}
}

function stripsearchkey($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = stripsearchkey($val);
		}
	} else {
		$string = trim($string);
		$string = str_replace('*', '%', addcslashes($string, '%_'));
		$string = str_replace('_', '\_', $string);
	}
	return $string;
}

function obclean() {
	global $_G;

	ob_end_clean();
	if ($_G['setting']['gzipcompress'] && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

//显示信息
function showmessage($message, $url_forward='', $second=3, $vars=array(), $checkresults = array()) {
	global $_G, $_SGLOBAL, $lang, $mlang, $_SC, $_SSCONFIG;

	if($message == "requirefiled_not_complate") {
		$error_details = "<ul>";
		foreach($checkresults as $key => $value) {
			foreach ($value as $k => $v) {
				$error_details .= '<li>'.$v.'</li>';
			}
		}
		$error_details .= "</ul>";
	}

	include_once(B_ROOT.'./language/message.lang.php');
	$message = ($mlang[$message]?$mlang[$message]:($_SGLOBAL['mlang'][$message] ? $_SGLOBAL['mlang'][$message] : $message));
	foreach ($vars as $key => $val) {
		$message = str_replace('{'.$key.'}', $val, $message);
	}
	if($_G['inajax'] == 1) {
		showxmlheader($_G['charset']);
		echo '<root>';
		if(!empty($checkresults)) {
			echo '<status>FAILED</status>';
			foreach($checkresults as $error) {
				echo showarraytoxml($error, $_G['charset'], 1);
			}
		} else {
			echo '<status>OK</status>';
			echo '<url><![CDATA['.$url_forward.']]></url>';
		}
		echo '<message><![CDATA['.$message.']]></message>';
		echo '</root>';
	} else {
		if($url_forward && empty($second)) {
			//直接301跳转
			obclean();
			header("HTTP/1.1 301 Moved Permanently");
			header("Location: $url_forward");
		} else {
			$tpl_file = 'templates/site/default/showmessage.html.php';
			$fullpath = 1;
			//显示
			obclean();
			if(!empty($url_forward)) {
				$second = $second * 1000;
				$message .= "<script>setTimeout(\"window.location.href ='$url_forward';\", $second);</script><ajaxok>";
			}

			include template($tpl_file, $fullpath);
			ob_out();
		}
	}
	exit();
}

function submitcheck($var, $checksec=0) {
	global $_G, $_SGLOBAL;

	if(!empty($_POST[$var]) && $_SERVER['REQUEST_METHOD'] == 'POST') {
		if((empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) && $_POST['formhash'] == formhash()) {
			if($_G['setting']['seccode'] && $checksec) {
				if(!empty($_POST['seccode'])) {
					if(ckseccode($_POST['seccode'])) {
						return true;
					}
					showmessage('incorrect_code');
				}
				return false;
			} else {
				return true;
			}
		} else {
			showmessage('submit_invalid');
		}
	} elseif (!empty($_GET[$var])) {
		if((empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) && $_GET['formhash'] == formhash()) {
			if($_G['setting']['seccode'] && $checksec) {
				if(!empty($_GET['seccode'])) {
					if(ckseccode($_GET['seccode'])) {
						return true;
					}
					showmessage('incorrect_code');
				}
				return false;
			} else {
				return true;
			}
		} else {
			showmessage('submit_invalid');
		}
	} else {
		return false;
	}
}

function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === false);
}

function shtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = shtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

//获取文件名后缀
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

function censor($message, $mod=0) {
	global $_G, $_SGLOBAL;
	@include_once(B_ROOT.'/data/system/censor.cache.php');
	if(!empty($_SGLOBAL['censor']) && is_array($_SGLOBAL['censor'])) {
		if($mod == 0) {
			if($_SGLOBAL['censor']['banned'] && preg_match($_SGLOBAL['censor']['banned'], $message)) {
				showmessage('words_can_not_publish_the_shield');
			}
			if($_SGLOBAL['censor']['mod'] && preg_match($_SGLOBAL['censor']['mod'], $message)) {
				showmessage('words_can_not_publish_the_shield');
			}
		} else {
			if(!empty($_SGLOBAL['censor']['banned'])) {
				$message = @preg_replace($_SGLOBAL['censor']['banned'], '**', $message);
			}

			if(!empty($_SGLOBAL['censor']['mod'])) {
				$message = @preg_replace($_SGLOBAL['censor']['mod'], '**', $message);
			}
		}

		if(!empty($_SGLOBAL['censor']['filter'])) {
			$message = @preg_replace($_SGLOBAL['censor']['filter']['find'], $_SGLOBAL['censor']['filter']['replace'], $message);
		}

	}
	return $message;
}

//读文件
function sreadfile($filename, $mode='r', $remote=0, $maxsize=0, $jumpnum=0) {
	if($jumpnum > 5) return '';
	$contents = '';

	if($remote) {
		$httpstas = '';
		$urls = initurl($filename);
		if(empty($urls['url'])) return '';

		$fp = @fsockopen($urls['host'], $urls['port'], $errno, $errstr, 20);
		if($fp) {
			if(!empty($urls['query'])) {
				fputs($fp, "GET $urls[path]?$urls[query] HTTP/1.1\r\n");
			} else {
				fputs($fp, "GET $urls[path] HTTP/1.1\r\n");
			}
			fputs($fp, "Host: $urls[host]\r\n");
			fputs($fp, "Accept: */*\r\n");
			fputs($fp, "Referer: $urls[url]\r\n");
			fputs($fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)\r\n");
			fputs($fp, "Pragma: no-cache\r\n");
			fputs($fp, "Cache-Control: no-cache\r\n");
			fputs($fp, "Connection: Close\r\n\r\n");

			$httpstas = explode(" ", fgets($fp, 128));
			if($httpstas[1] == 302 || $httpstas[1] == 302) {
				$jumpurl = explode(" ", fgets($fp, 128));
				return sreadfile(trim($jumpurl[1]), 'r', 1, 0, ++$jumpnum);
			} elseif($httpstas[1] != 200) {
				fclose($fp);
				return '';
			}

			$length = 0;
			$size = 1024;
			while (!feof($fp)) {
				$line = trim(fgets($fp, 128));
				$size = $size + 128;
				if(empty($line)) break;
				if(strexists($line, 'Content-Length')) {
					$length = intval(trim(str_replace('Content-Length:', '', $line)));
					if(!empty($maxsize) && $length > $maxsize) {
						fclose($fp);
						return '';
					}
				}
				if(!empty($maxsize) && $size > $maxsize) {
					fclose($fp);
					return '';
				}
			}
			fclose($fp);

			if(@$handle = fopen($urls['url'], $mode)) {
				if(function_exists('stream_get_contents')) {
					$contents = stream_get_contents($handle);
				} else {
					$contents = '';
					while (!feof($handle)) {
						$contents .= fread($handle, 8192);
					}
				}
				fclose($handle);
			} elseif(@$ch = curl_init()) {
				curl_setopt($ch, CURLOPT_URL, $urls['url']);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//timeout
				$contents = curl_exec($ch);
				curl_close($ch);
			} else {
				//无法远程上传
			}
		}
	} else {
		if(@$handle = fopen($filename, $mode)) {
			$contents = fread($handle, filesize($filename));
			fclose($handle);
		}
	}

	return $contents;
}

//写文件
function writefile($filename, $writetext, $filemod='text', $openmod='w', $eixt=1) {
	if(!@$fp = fopen($filename, $openmod)) {
		if($eixt) {
			exit('File :<br>'.srealpath($filename).'<br>Have no access to write!');
		} else {
			return false;
		}
	} else {
		$text = '';
		if($filemod == 'php') {
			$text = "<?php\n\n//Brand cache file, DO NOT modify me!".
				"\n//Created: ".date("M j, Y, G:i").
				"\n\nif(!defined('IN_BRAND')) exit('Access Denied');\n\n";
		}
		$text .= $writetext;
		if($filemod == 'php') {
			$text .= "; \n\n?>";
		}
		flock($fp, 2);
		fwrite($fp, $text);
		fclose($fp);
		return true;
	}
}

function initurl($url) {

	$newurl = '';
	$blanks = array('url'=>'');
	$urls = $blanks;

	if(strlen($url)<10) return $blanks;
	$urls = @parse_url($url);
	if(empty($urls) || !is_array($urls)) return $blanks;
	if(empty($urls['scheme'])) return $blanks;
	if($urls['scheme'] == 'file') return $blanks;

	if(empty($urls['path'])) $urls['path'] = '/';
	$newurl .= $urls['scheme'].'://';
	$newurl .= empty($urls['user'])?'':$urls['user'];
	$newurl .= empty($urls['pass'])?'':':'.$urls['pass'];
	$newurl .= empty($urls['host'])?'':((!empty($urls['user']) || !empty($urls['pass']))?'@':'').$urls['host'];
	$newurl .= empty($urls['port'])?'':':'.$urls['port'];
	$newurl .= empty($urls['path'])?'':$urls['path'];
	$newurl .= empty($urls['query'])?'':'?'.$urls['query'];
	$newurl .= empty($urls['fragment'])?'':'#'.$urls['fragment'];

	$urls['port'] = empty($urls['port'])?'80':$urls['port'];
	$urls['url'] = $newurl;

	return $urls;
}

//编译模板文件
function template($tplfile, $fullpath=0) {
	global $_G;

	if(empty($fullpath)) {
		$filename = 'templates/'.$_G['setting']['template'].'/'.$tplfile.'.html.php';
		if(!file_exists($filename)){
			$filename = 'templates/default/'.$tplfile.'.html.php';
		}
		$objfile = B_ROOT.'./data/cache/tpl/tpl_'.$_G['setting']['template'].'_'.$tplfile.'.php';
		$tplfile = B_ROOT.'./'.$filename;
	} else {
		$filename = $tplfile;
		$objfile = str_replace('/', '_', $filename);
		$objfile = B_ROOT.'./data/cache/tpl/tpl_'.$objfile.'.php';
		$tplfile = B_ROOT.'./'.$filename;
	}

	$tplrefresh = 1;
	if(file_exists($objfile)) {
		if(empty($_G['setting']['tplrefresh'])) {
			$tplrefresh = 0;
		} else {
			if(@filemtime($tplfile) <= @filemtime($objfile)) {
				$tplrefresh = 0;
			}
		}
	}

	if($tplrefresh) {
		include_once(B_ROOT.'./source/function/template.func.php');
		parse_template($tplfile, $objfile);
	}

	return $objfile;
}

//格式化路径
function srealpath($path) {
	$path = str_replace('./', '', $path);
	if(DIRECTORY_SEPARATOR == '\\') {
		$path = str_replace('/', '\\', $path);
	} elseif(DIRECTORY_SEPARATOR == '/') {
		$path = str_replace('\\', '/', $path);
	}
	return $path;
}

//模块
function block($thekey, $param) {
	global $_G, $_SGLOBAL, $_SBLOCK, $lang, $_BCACHE;
	$havethekey = false;
	$needcache = $multineedcache = 0;
	require_once(B_ROOT.'./source/function/block.func.php');

	$block_func = 'block_'.$thekey;
	if(!function_exists($block_func)) {
		$block_func = 'block_sql';
		$thekey = 'sql';
	}
	$_SBLOCK[$thekey] = array();

	//缓存key
	$cachekey = $multicachekey = smd5($thekey.$param);

	$paramarr = parseparameter($param);
	if(!empty($paramarr['uid'])) {
		$uid = $paramarr['uid'];
	} elseif (!empty($paramarr['authorid'])) {
		$uid = $paramarr['authorid'];
	} else {
		$uid = 0;
	}

	if(!empty($paramarr['perpage']) && !empty($_G['page'])) {
		//分页
		$cachekey = smd5($thekey.$param.$_G['page']);
	}

	if(!empty($paramarr['cachetime']) && $paramarr['cachetime']>0) {
		$cacheupdatetime = $paramarr['cachetime'];
	} else {
		$cacheupdatetime = 3600*24*30+rand(0, 1000);
		//默认缓存时间一个月
	}

	if($cacheupdatetime) {
		//获取缓存

		if(!empty($paramarr['perpage'])) {
			//获取分页计数缓存
			$_BCACHE->get($multicachekey);
			if(!isset($_SBLOCK[$multicachekey])) {
				$multineedcache = 1;//没有分页计数缓存
			} else {
				//创建下次更新时?
				if(!empty($_SBLOCK[$multicachekey]['filemtime'])) $_SBLOCK[$multicachekey]['updatetime'] = $_SBLOCK[$multicachekey]['filemtime'] + $cacheupdatetime; //文件缓存方式
				if(!empty($_SBLOCK[$multicachekey]['updatetime']) && $_SBLOCK[$multicachekey]['updatetime'] < $_G['timestamp']) {
					$multineedcache = 2; //需要更新
				}
			}
		}

		$_BCACHE->get($cachekey);
		if(!isset($_SBLOCK[$cachekey])) {
			$needcache = 1;//没有缓存
		} else {
			//创建下次更新时?
			if(!empty($_SBLOCK[$cachekey]['filemtime'])) $_SBLOCK[$cachekey]['updatetime'] = $_SBLOCK[$cachekey]['filemtime'] + $cacheupdatetime; //文件缓存方式
			if(!empty($_SBLOCK[$multicachekey]['updatetime']) && $_SBLOCK[$cachekey]['updatetime'] < $_G['timestamp']) {
				$needcache = 2;//需要更新
			}
		}
	}

	if($multineedcache && !empty($paramarr['perpage'])) {
		//分页计数缓存
		require_once(B_ROOT.'./source/function/block.func.php');
		$multicount = $block_func($paramarr, $multicachekey, 1);
		$_SBLOCK[$multicachekey]['value'] = serialize($multicount);
		$_SBLOCK[$multicachekey]['updatetime'] = $_G['timestamp'] + $cacheupdatetime;

		if($multineedcache == 1 || $multineedcache == 2) {
			$_BCACHE->set($multicachekey, $_SBLOCK[$multicachekey]['value'], $_SBLOCK[$multicachekey]['updatetime'], $paramarr['pagetype'], $paramarr['usetype'], $paramarr['shopid'], $paramarr['infoid']);
		}
	}

	if($needcache) {
		$theblockarr = array();

		require_once(B_ROOT.'./source/function/block.func.php');

		$theblockarr = $block_func($paramarr, $multicachekey);
		$_SBLOCK[$thekey] = $theblockarr;
		$havethekey = true;
		$_SBLOCK[$cachekey]['value'] = serialize($theblockarr);
		$_SBLOCK[$cachekey]['updatetime'] = $_G['timestamp'] + $cacheupdatetime;

		if($needcache == 1 || $needcache == 2) {
			//INSERT-UPDATE
			$_BCACHE->set($cachekey, $_SBLOCK[$cachekey]['value'], $_SBLOCK[$cachekey]['updatetime'], $paramarr['pagetype'], $paramarr['usetype'], $paramarr['shopid'], $paramarr['infoid']);
		}
	}
	if(!$havethekey) {
		$_SBLOCK[$thekey] = empty($_SBLOCK[$cachekey]['value'])?array():unserialize($_SBLOCK[$cachekey]['value']);
	}

	$iarr = $_SBLOCK[$thekey];
	if(!empty($paramarr['cachename'])) {
		$_SBLOCK[$paramarr['cachename'].'_listcount'] = !empty($_SBLOCK[$thekey]['listcount'])?$_SBLOCK[$thekey]['listcount']:0;
		$_SBLOCK[$paramarr['cachename'].'_multipage'] = empty($_SBLOCK[$thekey]['multipage'])?'':$_SBLOCK[$thekey]['multipage'];
		$_SBLOCK[$paramarr['cachename']] = $_SBLOCK[$thekey];
		unset($_SBLOCK[$paramarr['cachename']]['multipage'], $_SBLOCK[$paramarr['cachename']]['listcount']);
	}
	if(!empty($paramarr['tpl']) && $paramarr['tpl'] != 'data') {
		$paramarr['tpl'] = 'static/blockstyle/'.$paramarr['tpl'].'.html.php';
		include template($paramarr['tpl'], 1); 
	}
	return $cachekey;

}

function smd5($str) {
	return substr(md5($str), 8, 16);
}

function snl2br($message) {
	return nl2br(str_replace(array("\t", '   ', '  '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message));
}

//替换字符串中的特殊字符
//去掉指定字符串中\\或\'前的\
function sstripslashes($string) {

	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = sstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

function inserttable($tablename, $insertsqlarr, $returnid=0, $replace = false, $silent=0) {
	global $_G, $_SGLOBAL;

	$insertkeysql = $insertvaluesql = $comma = '';
	foreach ($insertsqlarr as $insert_key => $insert_value) {
		$insertkeysql .= $comma.'`'.$insert_key.'`';
		$insertvaluesql .= $comma.'\''.$insert_value.'\'';
		$comma = ', ';
	}
	$method = $replace?'REPLACE':'INSERT';

	DB::query($method.' INTO '.DB::table($tablename).' ('.$insertkeysql.') VALUES ('.$insertvaluesql.') ', $silent?'SILENT':'');
	if($returnid && !$replace) {
		return DB::insert_id();
	}
}

function deletetable($tablename, $wheresqlarr) {
	global $_G, $_SGLOBAL;

	if(empty($wheresqlarr)) {
		DB::query('TRUNCATE TABLE '.DB::table($tablename));
	} else {
		DB::query('DELETE FROM '.DB::table($tablename).' WHERE '.getwheresql($wheresqlarr));
	}
}

function updatetable($tablename, $setsqlarr, $wheresqlarr) {
	global $_G, $_SGLOBAL;

	$setsql = $comma = '';
	foreach ($setsqlarr as $set_key => $set_value) {
		$setsql .= $comma.$set_key.'=\''.$set_value.'\'';
		$comma = ', ';
	}
	DB::query('UPDATE '.DB::table($tablename).' SET '.$setsql.' WHERE '.getwheresql($wheresqlarr));
}

function getwheresql($wheresqlarr) {
	$result = $comma = '';
	if(empty($wheresqlarr)) {
		$result = '1';
	} elseif(is_array($wheresqlarr)) {
		foreach ($wheresqlarr as $key => $value) {
			$result .= $comma.$key.'=\''.$value.'\'';
			$comma = ' AND ';
		}
	} else {
		$result = $wheresqlarr;
	}
	return $result;
}

//写错误日志函数
function errorlog($type, $message, $halt = 0) {
	global $_G, $_SGLOBAL;
	@$fp = fopen(B_ROOT.'./log/errorlog.php', 'a');
	@fwrite($fp, "<?exit?>$_G[timestamp]\t$type\t$_G[uid]\t".str_replace(array("\r", "\n"), array(' ', ' '), trim(shtmlspecialchars($message)))."\n");
	@fclose($fp);
	if($halt) {
		exit();
	}
}

//调试信息,显示进程处理时间
function debuginfo($echo=1) {
	global $_G, $_SGLOBAL, $_BCACHE;

	$info = '';
	if(1==1 /*$_G['setting']['debug']*/) {
		$mtime = explode(' ', microtime());
		$totaltime = number_format(($mtime[1] + $mtime[0] - $_G['starttime']), 6);
		$info .= 'Processed in '.$totaltime.' second(s), ' . $_G['debug']['querynum'] .' queries. Cache '.
		$_BCACHE->getcachemode().' '.$_BCACHE->getallowcache().'.';
		$info .= '';
	}
	if($echo) {
		echo $info;
	} else {
		return $info;
	}
}

/**
 * 品牌空间的字符串长度计算（汉字和英文都算1个）
 * @param $string='', 需要计算的字符串
 * @param $charset, 字符集, gbk或utf8
 * @return 文字长度
 */
function bstrlen($string, $charset='') {
	global $_G, $_SC;
	if(empty($charset)) {
		$charset = $_G['charset'];
	}
	if(strtolower($charset) == 'gbk') {
		$charset = 'gbk';
	} else {
		$charset = 'utf8';
	}
	if(function_exists('mb_strlen')) {
		return mb_strlen($string, $charset);
	} else {
		$n = $noc = 0;
		$strlen = strlen($string);

		if($charset == 'utf8') {

			while($n < $strlen) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$n += 2; $noc++;
				} elseif(224 <= $t && $t <= 239) {
					$n += 3; $noc++;
				} elseif(240 <= $t && $t <= 247) {
					$n += 4; $noc++;
				} elseif(248 <= $t && $t <= 251) {
					$n += 5; $noc++;
				} elseif($t == 252 || $t == 253) {
					$n += 6; $noc++;
				} else {
					$n++;
				}
			}

		} else {

			while($n < $strlen) {
				$t = ord($string[$n]);
				if($t>127) {
					$n += 2; $noc++;
				} else {
					$n++; $noc++;
				}
			}

		}

		return $noc;
	}
}

/**
 * 品牌空间的字符串长度截断（汉字和英文都算1个）
 * @param $string='', 需要计算的字符串
 * @param $length='', 需要截断的字符长度
 * @param $havedot='', 截断后是否显示省略符号
 * @param $charset, 字符集, gbk或utf8
 * @return 文字长度
 */
function cutstr($string, $length, $havedot=0, $charset='') {
	global $_G, $_SC;
	if(empty($charset)) {
		$charset = $_G['charset'];
	}
	if(strtolower($charset) == 'gbk') {
		$charset = 'gbk';
	} else {
		$charset = 'utf8';
	}
	if(bstrlen($string, $charset) <= $length) {
		return $string;
	}
	if(function_exists('mb_strcut')) {
		$string = mb_substr($string, 0, $length, $charset);
	} else {
		$pre = '{%';
		$end = '%}';
		$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

		$strcut = '';
		$strlen = strlen($string);

		if($charset == 'utf8') {
			$n = $tn = $noc = 0;
			while($n < $strlen) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1; $n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2; $n += 2; $noc++;
				} elseif(224 <= $t && $t <= 239) {
					$tn = 3; $n += 3; $noc++;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4; $n += 4; $noc++;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5; $n += 5; $noc++;
				} elseif($t == 252 || $t == 253) {
					$tn = 6; $n += 6; $noc++;
				} else {
					$n++;
				}
				if($noc >= $length) {
					break;
				}
			}
			if($noc > $length) {
				$n -= $tn;
			}
			$strcut = substr($string, 0, $n);
		} else {
			while($n < $strlen) {
				$t = ord($string[$n]);
				if($t > 127) {
					$tn = 2; $n += 2; $noc++;
				} else {
					$tn = 1; $n++; $noc++;
				}
				if($noc >= $length) {
					break;
				}
			}
			if($noc > $length) {
				$n -= $tn;
			}
			$strcut = substr($string, 0, $n);
		}
		$string = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	}

	if($havedot) {
		$string = $string . "...";
	}

	return $string;
}

/**
 * 去除ubb代码
 * @param $str=''，字符串， $length截断长度
 * @return 字符串
 */
function messagecutstr($str, $length=255) {
	$bbcodes = 'b|i|u|p|color|size|font|align|list|indent|float';
	$bbcodesclear = 'url|email|code|free|table|tr|td|img|swf|flash|attach|media|audio|payto';
	$str = cutstr(strip_tags(preg_replace(array(
			"/\[hide=?\d*\](.+?)\[\/hide\]/is",
			"/\[quote](.*?)\[\/quote]/si",
			"/\[($bbcodesclear)=?.*?\].+?\[\/\\1\]/si",
			"/\[($bbcodes)=?.*?\]/i",
			"/\[\/($bbcodes)\]/i",
	), array(
			' !hidden! ',
			'',
			'',
			'',
			''
			), $str)), $length);
			return trim($str);
}

//生成分页URL地址集合
function multi($num, $perpage, $curpage, $mpurl, $phpurl=1) {

	global $_G, $_SHTML, $lang, $_SGLOBAL;
	//if(($curpage-1)*$perpage > $num) showmessage('start_listcount_error');

	$maxpages = $_SGLOBAL['maxpages'];
	$multipage = $a_name = '';
	if($phpurl) {
		$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	} else {
		$urlarr = $mpurl;
		unset($urlarr['php']);
		unset($urlarr['modified']);
	}
	if($num > $perpage) {
		$page = 10;
		$offset = 2;
		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $curpage + $page - $offset - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $curpage - $pages + $to;
				$to = $pages;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$from = $pages - $page + 1;
				}
			}
		}

		if($phpurl) {
			$url = $mpurl.'page=1'.$a_name;
			$url2 = $mpurl.'page='.($curpage - 1).$a_name;
		}

		$multipage = '<div class="pages cl"><div class="pg">'.($curpage - $offset > 1 && $pages > $page ? '<a href="'.$url.'">1...</a>' : '').($curpage > 1 ? '<a class="prev" href="'.$url2.'">'.$lang['pre_page'].'</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			if($phpurl) {
				$url = $mpurl.'page='.$i.$a_name;
			}
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' : '<a href="'.$url.'">'.$i.'</a>';
		}

		if($phpurl) {
			$url = $mpurl.'page='.($curpage + 1).$a_name;
			$url2 = $mpurl.'page='.$pages.$a_name;
		}

		$multipage .= ($to < $pages && $curpage < $maxpages ? '<a href="'.$url2.'" target="_self">...'.$realpages.'</a>' : '').
		($curpage < $pages ? '<a class="nxt" href="'.$url.'">'.$lang['next_page'].'</a>' : '').
		($pages > $page ? '' : '');
		$multipage .= '</div></div>';
	}
	return $multipage;
}

//跟SGMDATE函数对应
function sdate($dateformat, $timestamp, $format=0) {
	echo sgmdate($timestamp, $dateformat, $format);
}

//生成下拉框
function getselectstr($var, $optionarray, $value='', $other='') {
	global $_G, $_SGET;

	$selectstr = '<select id="'.$var.'" name="'.$var.'"'.$other.'>';
	foreach ($optionarray as $optionkey => $optionvalue) {
		$selectstr .= '<option value="'.$optionkey.'">'.$optionvalue.'</option>';
	}
	if($value=='' && isset($_SGET[$var])) {
		$value = $_SGET[$var];
	}
	$selectstr = str_replace('value="'.$value.'"', 'value="'.$value.'" selected', $selectstr);
	$selectstr .= '</select>';
	return $selectstr;
}

//在$sql前强制加上 SELECT
function getblocksql($sql) {
	$sql = trim($sql);
	$sql = str_replace(';', '', $sql);
	$sql = preg_replace("/^(select)/i", '', $sql);
	$sql = 'SELECT'.$sql;
//	$sql = stripslashes($sql);
	return $sql;
}

//读取指定目录下的文件
function sreaddir($dir, $ext='') {

	$filearr = array();
	if(is_dir($dir)) {
		$filedir = dir($dir);
		while(false !== ($entry = $filedir->read())) {
			if(!empty($ext)) {
				if (strtolower(fileext($entry)) == strtolower($ext)) {
					$filearr[$entry] = $entry;
				}
			} else {
				if($entry != '.' && $entry != '..') {
					$filearr[$entry] = $entry;
				}
			}
		}
		$filedir->close();
	}
	return $filearr;
}

//如果$string不是变量，则返回加上‘’的字符串
function getdotstring($string, $vartype, $allownull=false, $varscope=array(), $sqlmode=1, $unique=true) {

	if(is_array($string)) {
		$stringarr = $string;
	} else {
		if(substr($string, 0, 1) == '$') {
			return $string;
		}
		$string = str_replace('，', ',', $string);
		$string = str_replace(' ', ',', $string);
		$stringarr = explode(',', $string);
	}

	$newarr = array();
	foreach ($stringarr as $value) {
		$value = trim($value);
		if($vartype == 'int') {
			$value = intval($value);
		}
		if(!empty($varscope)) {
			if(in_array($value, $varscope)) {
				$newarr[] = $value;
			}
		} else {
			if($allownull) {
				$newarr[] = $value;
			} else {
				if(!empty($value)) $newarr[] = $value;
			}
		}
	}

	if($unique) $newarr = sarray_unique($newarr);

	if($vartype == 'int') {
		$string = implode(',', $newarr);
	} else {
		if($sqlmode) {
			$string = '\''.implode('\',\'', $newarr).'\'';
		} else {
			$string = implode(',', $newarr);
		}
	}
	return $string;
}

//将数组中相同的值去掉,同时将后面的键名也忽略掉
function sarray_unique($array) {
	$newarray = array();
	if(!empty($array) && is_array($array)) {
		$array = array_unique($array);
		foreach ($array as $value) {
			$newarray[] = $value;
		}
	}
	return $newarray;
}

//返回标准零时区时间戳
function sstrtotime($timestamp) {
	global $_G;

	$timestamp = trim($timestamp);	//过滤首尾空格
	if(empty($timestamp)) return 0;
	$hour = $minute = $second = $month = $day = $year = 0;
	$exparr = $timearr = array();
	if(strpos($timestamp, ' ') !== false && strpos($timestamp, '-') !== false) {
		$timearr = explode(' ', $timestamp);
		$exparr = explode('-', $timearr[0]);
		$year = empty($exparr[0])?0:intval($exparr[0]);
		$month = empty($exparr[1])?0:intval($exparr[1]);
		$day = empty($exparr[2])?0:intval($exparr[2]);
		$exparr = explode(':', $timearr[1]);
		$hour = empty($exparr[0])?0:intval($exparr[0]);
		$minute = empty($exparr[1])?0:intval($exparr[1]);
		$second = empty($exparr[2])?0:intval($exparr[2]);
	} elseif(strpos($timestamp, '-') !== false && strpos($timestamp, ' ') === false) {
		$exparr = explode('-', $timestamp);
		$year = empty($exparr[0])?0:intval($exparr[0]);
		$month = empty($exparr[1])?0:intval($exparr[1]);
		$day = empty($exparr[2])?0:intval($exparr[2]);
	} elseif(!strpos($timestamp, '-') === false && strpos($timestamp, ' ') !== false) {
		$exparr = explode(':', $timestamp);
		$hour = empty($exparr[0])?0:intval($exparr[0]);
		$minute = empty($exparr[1])?0:intval($exparr[1]);
		$second = empty($exparr[2])?0:intval($exparr[2]);
	} else {
		return 0;
	}
	return gmmktime($hour, $minute, $second, $month, $day, $year) - $_G['setting']['timeoffset'] * 3600;
}

//获取信息分类
function getcategory($type) {
	global $_SGLOBAL;
	@include_once(B_ROOT.'./data/system/'.$type.'category.cache.php');
	if(!isset($_SGLOBAL[$type.'cates']) || !is_array($_SGLOBAL[$type.'cates'])) {
		require_once(B_ROOT.'./source/function/cache.func.php');
		updatecategorysingle($type);
	}
	$categorylist = & $_SGLOBAL[$type.'cates'];
	return $categorylist;
}

//获取本店铺允许使用的模型分类
function mymodelcategory($mname, $pre='|----') {
	global $_G, $_SGLOBAL;
	$catlist = array();
	$categorylist = getcategory($mname, $pre);

	if(isset($_SGLOBAL['panelinfo']) && $_SGLOBAL['panelinfo']['group'][$mname.'_field'] == 'all') {
		foreach($categorylist as $cat) {
			//if($cat['havechild']==0) {
				$catlist[$cat['catid']] = $cat;
			//}
		}
		return $catlist;
	} elseif(isset($_SGLOBAL['panelinfo'])) {
		$f_id = $_SGLOBAL['panelinfo']['catid'];
		$s_id = DB::result_first( "SELECT upid FROM ".DB::table('categories')." WHERE catid = '".$f_id."'");
		while($s_id != '0') {
			$t_id = DB::result_first( "SELECT upid FROM ".DB::table('categories')." WHERE catid = '".$s_id."'");
			$f_id = $s_id;
			$s_id = $t_id;
		}

		$tmpquery = DB::result_first( "SELECT ".$mname."_field FROM ".DB::table('categories')." WHERE catid = '$f_id'");
		$tmparr = explode(',', $tmpquery);
		$mycatidarr = explode(',', $_SGLOBAL['panelinfo']['group'][$mname.'_field']);
		$mycatidarr = array_unique(array_merge($tmparr,$mycatidarr));
		foreach($mycatidarr as $catid) {
			//if($catid == $categorylist[$catid]['subcatid']) {
				$catlist[$catid] = $categorylist[$catid];
			//}
		}
		return $catlist;
	} else {
		return array();
	}
}

//获取点评模型
function getcommentmodel($cmid) {
	global $_G, $_SGLOBAL;

	$commentmodelarr = array();
	$query = DB::query('SELECT * FROM '.DB::table('commentmodels').' WHERE `cmid`=\''.$cmid.'\'');
	if($commentmodelarr = DB::fetch($query)) {
		$commentmodelarr['scorename'] = unserialize($commentmodelarr['scorename']);
	}

	return $commentmodelarr;
}

//获取店长ID
function getshopuid($type) {
	global $_G, $_SGLOBAL, $item;

	if($type == 'shop') {
		return $item['uid'];
	} else {
		$shopuid = DB::result_first('SELECT uid FROM '.DB::table('shopitems').' WHERE `itemid`=\''.$item['shopid'].'\'');
		return $shopuid;
	}
}

function strim($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = strim($val);
		}
	} else {
		$string = trim($string);
	}
	return $string;
}

function scensor($string, $mod=0) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = scensor($val, $mod);
		}
	} else {
		$string = censor($string, $mod);
	}
	return $string;
}

//获取用户数据
function getpassport($username, $password) {
	$passport = array();
	if(!@include_once B_ROOT.'./uc_client/client.php') {
		showmessage('system_error');
	}

	$ucresult = uc_user_login($username, $password);
	if($ucresult[0] > 0) {
		$passport['uid'] = $ucresult[0];
		$passport['username'] = $ucresult[1];
		$passport['email'] = $ucresult[3];
	}
	return $passport;
}

//产生form防伪码
function formhash() {
	global $_G, $_SGLOBAL;

	if(empty($_SGLOBAL['formhash'])) {
		$hashadd = (defined('IN_ADMIN') || defined('IN_STORE')) ? 'Only For BRAND Admin OR Panel' : '';
		$_SGLOBAL['formhash'] = substr(md5(substr($_G['timestamp'], 0, -7).'|'.$_G['uid'].'|'.md5($_G['setting']['sitekey']).'|'.$hashadd), 8, 8);
	}
	return $_SGLOBAL['formhash'];
}

//检查验证码
function ckseccode($seccode) {
	global $_G, $_SCOOKIE;

	$check = true;
	$cookie_seccode = empty($_G['cookie']['seccode'])?'':authcode($_G['cookie']['seccode'], 'DECODE');
	if(empty($cookie_seccode) || strtolower($cookie_seccode) != strtolower($seccode)) {
		$check = false;
	}
	return $check;
}

//判断是否设置论坛
function exists_discuz() {
	global $_G, $_SC;
	if(!empty($_SC['bbs_url'])) {
		return true;
	} else {
		return false;
	}
}

//检查邮箱是否有效
function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//通过某物件得到所属店铺的店铺组ID
function getgroupid($type, $itemid) {
	global $_G, $_SGLOBAL;

	if($type == 'shop') {
		$shopid = $itemid;
	} else {
		$shopid = DB::result_first('SELECT shopid FROM '.DB::table($type.'items').' WHERE itemid=\''.$itemid.'\'');
	}
	$groupid = DB::result_first('SELECT groupid FROM '.DB::table('shopitems').' WHERE itemid=\''.$shopid.'\'');

	return $groupid;
}

/**
 * 检查是否操作创始人
 */
function ckfounder($uid) {
	global $_G, $_SC;

	$founders = empty($_SC['founder'])?array():explode(',', $_SC['founder']);
	return in_array($uid, $founders);
}

function formatcomment($comment, $repeatids = array(), $style=0) {
	global $_G, $lang;

	include_once(B_ROOT.'./source/function/misc.func.php');
	$searcharr = $replacearr = array();
	$comment['message'] = snl2br($comment['message']);

	if(empty($comment['author'])) $comment['author'] = 'Guest';
	$comment['hideauthor'] = (!empty($comment['hideauthor']) && !empty($_G['setting']['commanonymous'])) ? 1 : 0;
	$comment['hideip'] = (!empty($comment['hideip']) && !empty($_G['setting']['commhideip'])) ? 1 : 0;
	$comment['hidelocation'] = (!empty($comment['hidelocation']) && !empty($_G['setting']['commhidelocation'])) ? 1 : 0;
	$comment['iplocation'] = str_replace(array('-', ' '), '', convertip($comment['ip']));
	$comment['ip'] = preg_replace("/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/", "\$1.\$2.*.*", $comment['ip']);

	$_G['setting']['commfloornum'] = intval($_G['setting']['commfloornum']);
	$comment['floornum'] = intval($comment['floornum']);
	if(!$style) {

		if(!empty($_G['setting']['commfloornum'])) {
			//削楼功能
			if($_G['setting']['commfloornum'] < $comment['floornum']) {
				$cutfloor = $comment['floornum'] - $_G['setting']['commfloornum'];
				$searchstr = "/\<div id=\"cid_{$comment['cid']}_$cutfloor\".*?\<div id=\"cid_{$comment['cid']}_".($cutfloor+1)."_title\"/is";
				$replacestr = "<div id=\"cid_{$comment['cid']}_".($cutfloor+1)."_title\"";
				$comment['message'] = preg_replace($searchstr, $replacestr, $comment['message']);
			}

		} else {
			//高层电梯
			if($comment['floornum'] > 49) {
				$elevatordetail = <<<EOF
						<div id="cid_{$comment['cid']}_elevator" class="floor_op">
							<div class="old_title "><span class="author">$lang[comment_elevator]</span><span class="color_red">$lang[comment_floor_hide]</span></div>
							<p class="detail "><span><a class="color_red" href="javascript:;" onclick="elevator($comment[cid], 2);" title="$lang[comment_floor_up_title]">[{$lang['comment_floor_up']}]</a>
							<a class="color_red" href="javascript:;" onclick="elevator($comment[cid], 1);" title="$lang[comment_floor_down_title]">[{$lang['comment_floor_down']}]</a></span>
							$lang[comment_floor_total]{$comment['floornum']}$lang[comment_floor_total_2]</p>
							<input type="hidden" id="cid_{$comment['cid']}_elevatornum" value="40">
							<input type="hidden" id="cid_{$comment['cid']}_floornum" value="$comment[floornum]">
						</div>
EOF;
							$searcharr[] = '<div id="cid_'.$comment['cid'].'_'.($comment['floornum']-8).'_title"';
							$replacearr[] = $elevatordetail.'<div id="cid_'.$comment['cid'].'_'.($comment['floornum']-8).'_title"';
							if(!in_array($comment['firstcid'], $repeatids)) {
								for ($i=41; $i < $comment['floornum']-8; $i++) {
									$searcharr[] = "id=\"cid_{$comment['cid']}_{$i}\" class=\"old\"";
									$searcharr[] = "id=\"cid_{$comment['cid']}_{$i}_title\" class=\"old_title\"";
									$searcharr[] = "id=\"cid_{$comment['cid']}_{$i}_detail\" class=\"detail\"";
									$replacearr[] = "id=\"cid_{$comment['cid']}_{$i}\" class=\"hideold\"";
									$replacearr[] = "id=\"cid_{$comment['cid']}_{$i}_title\" class=\"hideelement\"";
									$replacearr[] = "id=\"cid_{$comment['cid']}_{$i}_detail\" class=\"hideelement\"";
								}
							}
			}

		}

		//隐藏重复盖楼
		if(!empty($_G['setting']['commhidefloor']) && in_array($comment['firstcid'], $repeatids)) {
			$tipdetail = "<p id=\"cid_{$comment['cid']}_tip_detail\" class=\"hidetip\">$lang[comment_floor_repeat] <a class=\"color_red\" href=\"javascript:;\" onclick=\"operatefloor({$comment['cid']});\">[{$lang['comment_floor_view_repeat']}]</a><p></div>";
			$searcharr[] = 'class="old"';
			$searcharr[] = 'class="old_title"';
			$searcharr[] = 'class="detail"';
			$searcharr[] = 'class="floor_op"';
			$searcharr[] = '_1" class="hideold"';
			$searcharr[] = '_tip" class="hideold"';
			$searcharr[] = '_1_title" class="hideelement"';
			$searcharr[] = '_1_detail" class="hideelement"';
			$searcharr[] = '<div class="new"';

			$replacearr[] = 'class="hideold"';
			$replacearr[] = 'class="hideelement"';
			$replacearr[] = 'class="hideelement"';
			$replacearr[] = 'class="hideelement"';
			$replacearr[] = '_1" class="old"';
			$replacearr[] = '_tip" class="old"';
			$replacearr[] = '_1_title" class="old_title"';
			$replacearr[] = '_1_detail" class="detail"';
			$replacearr[] = $tipdetail.'<div class="new"';

			$comment['message'] = "<div id=\"cid_{$comment['cid']}_tip\" class=\"old\">".$comment['message'];

		}

		$comment['message'] = str_replace($searcharr, $replacearr, $comment['message']);

	} else {

		preg_match_all ("/\<div class=\"new\">(.+)?\<\/div\>/is", $comment['message'], $currentmessage, PREG_SET_ORDER);
		if(!empty($currentmessage)) $comment['message'] = $currentmessage[0][0];
		$comment['message'] = preg_replace("/\<div class=\"quote\"\>\<blockquote.+?\<\/blockquote\>\<\/div\>/is", '',$comment['message']);

	}
	return $comment;
}

//公告标题样式生成函数
function pktitlestyle($styletitle) {
	$styletitle = substr($styletitle, 1);
	if(empty($styletitle)) {
		return '';
	} else {
		$return = '';
		substr($styletitle,6,1) == 1?$em = 'italic':$em = 'none';
		substr($styletitle,7,1) == 1?$strong = 'bold':$strong = 'none';
		substr($styletitle,8,1) == 1?$underline = 'underline':$underline = 'none';
		$color = trim(substr($styletitle,0,6));
		if(!empty($color)){
			$return .= 'color:#'.$color.";";
		}
		$return .= 'font-style:'.$em.';font-weight:'.$strong.';text-decoration:'.$underline;
		return $return;
	}
}

if(!function_exists('htmlspecialchars_decode')) {
	//兼容php 5.0
	function htmlspecialchars_decode($text){
		return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
	}
}

//取得系统设置
function refreshbrandsetting() {
	global $_G, $_SGLOBAL, $_SSCONFIG, $_SC, $lang;

	$cachefile = B_ROOT.'./data/system/config.cache.php';

	if(!file_exists($cachefile)) {
		require_once(B_ROOT.'./source/function/cache.func.php');
		updatesettingcache();
		@header('Location: '.$_SERVER['REQUEST_URI']);
		exit;
	}
}

// 检查各种过期状态
function ck_item_status($itemid, $mname, $showmessage = 1, $shopid = 0) {
	global $_G, $_SGLOBAL;
	$selectsql = $wheresql = '';
	$itemid = intval($itemid);
	$is_out_date = false;

	if($mname=='index') $mname='shop';

	if(empty($mname) || !in_array($mname, array('shop','good','notice','consume','groupbuy'))) {
		$selectsql = 'SELECT grade FROM ';
	} else {
		$selectsql = 'SELECT grade, validity_end FROM ';
	}

	if($mname == 'shop') {
		$wheresql = " itemid='$itemid'";
	} else {
		$wheresql = " itemid='$itemid' AND shopid='$shopid'";
	}

	$sql = $selectsql.DB::table($mname.'items')." WHERE $wheresql";

	$status = DB::fetch(DB::query($sql));
	if(!$status) {
		if($showmessage > 0) {
			showmessage('not_found', 'index.php');
		}
		return false;
	}

	if(intval($status['grade']) < 3){
		$is_out_date = true;
	} elseif(!in_array($mname, array('album', 'photo'))) {
		if($status['validity_end'] != '0' && ($status['validity_end'] < $_G['timestamp'])){
			DB::query('UPDATE '.DB::table($mname.'items')." SET grade='2' WHERE itemid='$itemid'");
			$is_out_date = true;
		}
	}

	if($is_out_date && $showmessage == 1){
		if($mname == 'shop'){
			showmessage('shop_close', 'index.php');
		} else {
			showmessage('not_found', 'index.php');
		}
	}
	return $is_out_date;
}

/**
 * 加载 Class
 *
 * @param $m 类名
 * @param $param 实例化参数
 */
function loadClass($m, $param = ''){
	if(!require_once(B_ROOT.'./source/class/'.$m.'.class.php')){
		die('Class load error : no file exists ! the file must be the same name as classname and replaced in ./source/class/ ');
	}

	$_m = new $m($param);
	return $_m;
}

/**
 * 初始化 缓存的class
 */
function data_cache_start() {
	global $_G, $_BCACHE;
	if(empty($_BCACHE)) {
		require_once(B_ROOT.'./source/class/data_cache.class.php');
		$_BCACHE = new bcache($_G['setting']['cachemode'], $_G['setting']['cachegrade'], $_G['setting']['allowcache']);
	}
}

/**
 * 取得附件图片URL路径（多服务器冗余）
 * @param $url=''，附件表记录的图片相对位置
 * @param $thumb, 检测并返回缩略图
 * @param $nopicurl，检测到图片不存在时使用的无图提示图片URL
 * @param $force，强制返回图片URL
 * @return 图片URL
 */
function getattachurl($url='', $thumb=0, $nopicurl='', $force=0) {
	global $_G;
	$url = trim($url);
	$nopicurl = trim($nopicurl);
	if(!$nopicurl) {
		$nopicurl = 'static/image/nophoto.gif';
	}
	if($force || strpos($url, 'http://') === 0) {
		$url = $url;
	} elseif($url && file_exists(A_DIR.'/'.$url)) {
		//原始图片检查
		if($_G['setting']['attachmenturlcount']>1) {
			//附件多域名，基本平均分布算法
			$this_a = ord(substr($url, -12, -11))%$_G['setting']['attachmenturlcount'];
			$this_aurl = $_G['setting']['attachmenturlarr'][$this_a];
		} else {
			$this_aurl = A_URL;
		}

		if($thumb && file_exists(A_DIR.'/'.$url.'.thumb.jpg')) {
			//调用缩略图检查
			$url = $this_aurl.'/'.$url.'.thumb.jpg';
		}elseif($thumb && file_exists(A_DIR.'/'.substr($url,0,-4).'.thumb.jpg')) {
			//调用缩略图2次检查
			if(@rename(A_DIR.'/'.substr($url,0,-4).'.thumb.jpg', A_DIR.'/'.$url.'.thumb.jpg')) {
				$url = $this_aurl.'/'.$url.'.thumb.jpg';
			} else {
				$url = $this_aurl.'/'.substr($url,0,-4).'.thumb.jpg';
			}
		} else {
			$url = $this_aurl.'/'.$url;
		}
	} else {
		$url = $nopicurl;
	}
	return $url;
}

function mktempthumb($source, $thumbwidth = 200, $thumbheight = 200) {
	$isthumb =0;

	$thumbwidth = $thumbwidth > 10 && $thumbwidth < 1000 ? intval($thumbwidth) : 200;
	$thumbheight = $thumbheight > 10 && $thumbheight < 1000 ? intval($thumbheight) : 200;

	if(empty($source) || !file_exists(A_DIR.'/'.$source)) {
		$source = B_ROOT.'static/image/nophotosmall.gif';
	} else {
		$source = A_DIR.'/'.$source;
	}
	$target = 'temp/'.smd5($source.$thumbwidth.$thumbheight).'.temp.jpg';

	if(!file_exists(A_DIR.'/'.$target)) {
		$isthumb = loadClass('image')->Thumb($source, $target, $thumbwidth, $thumbheight);
		if(!$isthumb) {
			$isthumb = @copy($source, A_DIR.'/'.$target);
		}
	} else {
		$isthumb = 1;
	}

	if($isthumb) {
		return $target;
	} else {
		return $source;
	}

}

//取GB2312字符串首字母,原理是GBK汉字是按拼音顺序编码的
//如果是utf8的则转为gbk的，再进行取就行了
function getletter($input) {
	global $_G;

	$dict = array(
		'a'=>0xB0C4,
		'b'=>0xB2C0,
		'c'=>0xB4ED,
		'd'=>0xB6E9,
		'e'=>0xB7A1,
		'f'=>0xB8C0,
		'g'=>0xB9FD,
		'h'=>0xBBF6,
		'j'=>0xBFA5,
		'k'=>0xC0AB,
		'l'=>0xC2E7,
		'm'=>0xC4C2,
		'n'=>0xC5B5,
		'o'=>0xC5BD,
		'p'=>0xC6D9,
		'q'=>0xC8BA,
		'r'=>0xC8F5,
		's'=>0xCBF9,
		't'=>0xCDD9,
		'w'=>0xCEF3,
		'x'=>0xD188,
		'y'=>0xD4D0,
		'z'=>0xD7F9,
	);

	$str_1 = substr($input, 0, 1);
	if(ctype_alpha($str_1)) {
		return strtolower($str_1);
	} elseif($str_1 >= chr(0x81) && $str_1 <= chr(0xfe)) {
		$num = hexdec(bin2hex(substr($input, 0, 2)));
		foreach ($dict as $k=>$v){
			if($v>=$num) {
				break;
			}
		}
		return $k;
	} elseif(is_numeric($str_1)) {
		switch($str_1) {
			case '1':
				$str_1 = 'y';
				break;
			case '2':
				$str_1 = 'e';
				break;
			case '3':
			case '4':
				$str_1 = 's';
				break;
			case '5':
				$str_1 = 'w';
				break;
			case '6':
			case '0':
				$str_1 = 'l';
				break;
			case '7':
				$str_1 = 'q';
				break;
			case '8':
				$str_1 = 'b';
				break;
			case '9':
				$str_1 = 'j';
				break;
			default:
				$str_1 = 'u';
				break;
		}
		return $str_1;
	} else {
		return 'others';
	}
}

function showxmlheader($encoding='GBK') {
	global $_G;
	obclean();
	@header("Expires: -1");
	@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", false);
	@header("Pragma: no-cache");
	@header('Content-type: application/xml; charset='.$encoding);
	echo "<?xml version=\"1.0\" encoding=\"$encoding\"?>\n";
}

function showarraytoxml($phparray = array(), $encoding='GBK', $unityitem=0) {
	global $_G, $_SC;
	$phparray = biconv($phparray, $_G['charset'], $encoding, 1);
	$retxml = '';
	foreach($phparray as $key=>$value) {
		if($key && $value) {
			if(is_numeric($key)) { $key = 'key_'.$key;}
			if(is_array($value)) {
				$retxml .= "\n<$key>\n";
				$retxml .= showarraytoxml($value);
				$retxml .= "</$key>\n";
			} else {
				if($unityitem) {
					$key = str_replace(array('[', ']'), '_', $key);
					$retxml .= "<item name='$key'><![CDATA[$value]]></item>\n";
				} else {
					$retxml .= "<$key><![CDATA[$value]]></$key>\n";
				}
			}
		}
	}
	return $retxml;
}

function biconv($string, $from='GBK', $to='UTF-8', $ignore=1) {
	if(strncasecmp($from, $to, 3)==0) {
		//两字符串前3个字节忽略大小写相等，不需要转换编码
		return $string;
	}
	if(is_array($string)) {
		foreach($string as $key=>$value) {
			$string[$key] = biconv($value, $from, $to, $ignore);
		}
	} else {
		if(function_exists('mb_convert_encoding')) {
			$string = mb_convert_encoding($string, $to, $from);
		} else {
			$string = iconv($from, $to.($ignore?'//IGNORE':''), $string);
		}
	}
	return $string;
}

/**
 * 将地区分类转成json
 */
function json_encode_region($sourcearr) {
	global $_G, $_SC;
	if(!function_exists("json_encode")) {
		$com = "";
		$json = "{";
		if(!empty($sourcearr)){
			foreach($sourcearr as $key=>$value) {
				if(is_array($value)) {
					$json_node = "\"$key\":".json_encode_region($value);
				} else {
					$json_node = "\"$key\":\"$value\"";
				}
				$json .= $com. $json_node;
				$com = ", ";
			}
		}
		return $json."}";
	} else {
		$sourcearr = biconv($sourcearr, $_G['charset'], 'UTF-8');
		return json_encode($sourcearr);
	}
}

/**
 * 更新信息统计
 */
function updateshopitemnum($type, $shopid = '') {
	global $_G, $_SGLOBAL, $_POST;

	$pernum = intval($_POST[$type.'_updateshopitemnum']);
	$cronshopid = !empty($shopid) ? $shopid : 0;
	$resultarr = array();
	$shopnum = DB::result_first('SELECT COUNT(itemid) FROM '.DB::table('shopitems').' WHERE itemid>\''.$cronshopid.'\' ORDER BY itemid ASC');
	$query = DB::query('SELECT itemid FROM '.DB::table('shopitems').' WHERE itemid>\''.$cronshopid.'\' ORDER BY itemid ASC LIMIT '.$pernum);
	while($value = DB::fetch($query)) {
		$itemnum = 0;
		if($type == 'brandlinks') {
			$itemnum = DB::result_first('SELECT COUNT(linkid) FROM '.DB::table('brandlinks').' WHERE shopid=\''.$value['itemid'].'\'');
		} else {
			$othersql = $type == 'album' ? 'AND frombbs=0' : '';
			$itemnum = DB::result_first('SELECT COUNT(itemid) FROM '.DB::table($type.'items').' WHERE shopid=\''.$value['itemid'].'\' '.$othersql);
		}
		DB::query('UPDATE '.DB::table('shopitems').' SET itemnum_'.$type.'=\''.$itemnum.'\' WHERE itemid=\''.$value['itemid'].'\'');
		$resultarr[] = $value;
	}
	if(($shopnum > $pernum)) {
		$cronlastshop = array_pop($resultarr);
		$cronshopid = $cronlastshop['itemid'];
		updateshopitemnum($type, $cronshopid);
	}
	cpmsg('message_success', $_SERVER['SCRIPT_NAME'].'?action=tool&operation=updateshopitemnum');
}

function sizecount($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

/**
 * 循环建立文件夹
 *
 * @param string $dir
 * @param string $mode
 */
function dmkdir($dir, $mode = 0777){
	if(!is_dir($dir)) {
		dmkdir(dirname($dir));
		@mkdir($dir, $mode);
		@touch($dir.'/index.htm'); @chmod($dir.'/index.htm', 0777);
	}
	return true;
}

/**
 * 写日志
 *
 * @param $file 日志文件
 * @param $log 日志内容
 */
function writelog($file, $log) {
	global $_G, $_SGLOBAL;

	$yearmonth = sgmdate($_G['timestamp'], 'Ym');
	$logdir = B_ROOT.'./data/log/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
		}
		fclose($fp);
	}
}

function implodearray($array, $skip = array()) {

	$return = '';
	if(is_array($array) && !empty($array)) {
		foreach ($array as $key => $value) {
			if(empty($skip) || $key === 0 || !in_array($key, $skip)) {
				if(is_array($value)) {
					$return .= "$key={".implodearray($value, $skip)."}; ";
				} else {
					$return .= "$key=$value; ";
				}
			}
		}
	}
	return $return;
}

function clearlogstring($str) {

	if(!empty($str)) {
		if(!is_array($str)) {
			$str = shtmlspecialchars(trim($str));
			$str = str_replace(array("\t", "\r\n", "\n", "   ", "  "), ' ', $str);
		} else {
			foreach ($str as $key => $val) {
				$str[$key] = clearlogstring($val);
			}
		}
	}
	return $str;
}

function getrootcatid($catid) {
	global $_G, $_SGLOBAL;

	if($_SGLOBAL['shopcates'][$catid]['upid'] != 0) {
		$catid = getrootcatid($_SGLOBAL['shopcates'][$catid]['upid']);
	}

	return $catid;
}

function libfile($libname, $folder = '') {
	$libpath = B_ROOT.'/source/'.$folder;
	if(strstr($libname, '/')) {
		list($pre, $name) = explode('/', $libname);
		return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
	} else {
		return realpath("{$libpath}/{$libname}.php");
	}
}

function updatestat($type, $primary = 0) {
	global $_G;

	if(empty($_G['uid'])) return false;

	$nowdaytime = sgmdate($_G['timestamp'], 'Ymd');
	if($primary) {
		$setarr = array(
			'uid' => $_G['uid'],
			'daytime' => $nowdaytime,
			'type' => $type
		);
		if(getcount('statuser', $setarr)) {
			return false;
		} else {
			DB::insert('statuser', $setarr);
		}
	}
	if(getcount('stat', array('daytime'=>$nowdaytime))) {
		DB::query("UPDATE ".DB::table('stat')." SET `$type`=`$type`+1 WHERE daytime='$nowdaytime'");
	} else {
		DB::query("DELETE FROM ".DB::table('statuser')." WHERE daytime != '$nowdaytime'");
		DB::insert('stat', array('daytime'=>$nowdaytime, $type=>'1'));
	}
	DB::query("UPDATE ".DB::table('settings')." SET `value`=`value`+1 WHERE variable='viewnum'");
}

function getcount($tablename, $condition) {

	if(empty($condition)) {
		$where = '1';
	} elseif(is_array($condition)) {
		$where = DB::implode_field_value($condition, ' AND ');
	} else {
		$where = $condition;
	}
	$row = DB::fetch_first("SELECT COUNT(*) AS num FROM ".DB::table($tablename)." WHERE $where");
	return $row['num'];
}

function loadcache($cachenames, $force = false) {
	global $_G;
	static $loadedcache = array();
	$cachenames = is_array($cachenames) ? $cachenames : array($cachenames);
	$caches = array();
	foreach ($cachenames as $k) {
		if (!isset($loadedcache[$k]) || $force) {
			$caches[] = $k;
			$loadedcache[$k] = true;
		}
	}

	if(!empty($caches)) {
		$cachedata = cachedata($caches);
		foreach($cachedata as $cname => $data) {
			if($cname == 'setting') {
				$_G['setting'] = $data;
			} elseif(strexists($cname, 'usergroup_'.$_G['groupid'])) {
				$_G['cache'][$cname] = $_G['perm'] = $_G['group'] = $data;
			} elseif(!$_G['uid'] && strexists($cname, $_G['setting']['newusergroupid'])) {
				$_G['perm'] = $data;
			} elseif($cname == 'style_default') {
				$_G['cache'][$cname] = $_G['style'] = $data;
			} elseif($cname == 'grouplevels') {
				$_G['grouplevels'] = $data;
			} else {
				$_G['cache'][$cname] = $data;
			}
		}
	}
	return true;
}

function cachedata($cachenames) {
	global $_G;
	static $isfilecache, $allowmem;

	$isfilecache = true;
	$allowmem = false;

	$data = array();
	$cachenames = is_array($cachenames) ? $cachenames : array($cachenames);

	if($isfilecache) {
		$lostcaches = array();
		foreach($cachenames as $cachename) {
			if(!@include_once(B_ROOT.'./data/cache/cache_'.$cachename.'.php')) {
				$lostcaches[] = $cachename;
			}
		}
		if(!$lostcaches) {
			return $data;
		}
		$cachenames = $lostcaches;
		unset($lostcaches);
	}
	$query = DB::query("SELECT /*!40001 SQL_CACHE */ * FROM ".DB::table('common_syscache')." WHERE cname IN ('".implode("','", $cachenames)."')");
	while($syscache = DB::fetch($query)) {
		$data[$syscache['cname']] = $syscache['ctype'] ? unserialize($syscache['data']) : $syscache['data'];
		$allowmem && (memory('set', $syscache['cname'], $data[$syscache['cname']]));
		if($isfilecache) {
			$cachedata = '$data[\''.$syscache['cname'].'\'] = '.var_export($data[$syscache['cname']], true).";\n\n";
			if($fp = @fopen(B_ROOT.'./data/cache/cache_'.$syscache['cname'].'.php', 'wb')) {
				fwrite($fp, "<?php\n//Brand cache file, DO NOT modify me!\n//Identify: ".md5($syscache['cname'].$cachedata.$_G['config']['security']['authkey'])."\n\n$cachedata?>");
				fclose($fp);
			}
		}
	}

	foreach($cachenames as $name) {
		if($data[$name] === null) {
			$data[$name] = null;
			$allowmem && (memory('set', $name, array()));
		}
	}

	return $data;
}

function setglobal($key , $value, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: $_G[$k[0]] = $value; break;
		case 2: $_G[$k[0]][$k[1]] = $value; break;
		case 3: $_G[$k[0]][$k[1]][$k[2]] = $value; break;
		case 4: $_G[$k[0]][$k[1]][$k[2]][$k[3]] = $value; break;
		case 5: $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] =$value; break;
	}
	return true;
}

function getglobal($key, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: return isset($_G[$k[0]]) ? $_G[$k[0]] : null; break;
		case 2: return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null; break;
		case 3: return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null; break;
		case 4: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null; break;
		case 5: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null; break;
	}
	return null;
}

function domaincheck($domain, $domainroot, $domainlength, $itemid = '') {
	global $checkresults;

	if(strlen($domain) < $domainlength) {
		$domain_length_error = str_replace('{length}', $domainlength, lang('domain_length_error'));
		array_push($checkresults, array('domain'=>$domain_length_error));
	} elseif(strlen($domain) > 30) {
		array_push($checkresults, array('domain'=>lang('two_domain_length_not_more_than_30_characters')));
	} elseif(!preg_match("/^[a-z][a-z0-9]*$/", $domain)) {
		array_push($checkresults, array('domain'=>lang('only_two_names_from_english_composition_and_figures')));
	} elseif(isholddomain($domain)) {
		array_push($checkresults, array('domain'=>lang('domain_be_retained')));
	} elseif(existdomain($domain, $domainroot, $itemid)) {
		array_push($checkresults, array('domain'=>lang('two_domain_have_been_occupied')));
	}

	if(!empty($checkresults)) {
		cpmsg('addobject_error', '', '', '', true, true, $checkresults);
	}

	return true;
}

function isholddomain($domain) {
	global $_G;

	$domain = strtolower($domain);
	if(preg_match("/^[^a-z]/i", $domain)) return true;
	$holdmainarr = empty($_G['setting']['holddomain'])?array('www'):explode('|', $_G['setting']['holddomain']);
	$ishold = false;
	foreach ($holdmainarr as $value) {
		if(strpos($value, '*') === false) {
			if(strtolower($value) == $domain) {
				$ishold = true;
				break;
			}
		} else {
			$value = str_replace('*', '.*?', $value);
			if(@preg_match("/$value/i", $domain)) {
				$ishold = true;
				break;
			}
		}
	}
	return $ishold;
}

function existdomain($domain, $domainroot, $itemid = '') {
	global $_G;

	$exist = false;
	$existitemid = DB::result_first('SELECT itemid FROM '.DB::table('shopitems').' WHERE `itemid`!=\''.$itemid.'\' AND `domain`=\''.$domain.'\'');
	if($existitemid) {
		$exist = true;
	}
	return $exist;
}

function adshow($parameter, $varname) {
	global $_G;
	if($_G['inajax']) {
		return;
	}
	$params = explode('/', $parameter);
	$cache_file = B_ROOT."data/system/ad_".$params[0].".cache.php";

	if (in_array($params[0], array("couplebanner", "float"))) {
		// 悬浮广告可以关闭
		if (($params[0] == "float" || $params[0] == "couplebanner") && $_G['cookie']['adclose_'] == 1) return ;
		$ad_close .= "<br /><a onclick=\"setcookie('adclose_', 1, 86400);this.parentNode.style.display='none'\" href=\"javascript:;\"><img src=\"static/image/ad_close.gif\"></a>";
	}

	if (file_exists($cache_file)) {
		require_once $cache_file;
		$ad_count = 0;
		foreach ($_G['cache']['ad'][$params[0]] as $v) {
			$v['targets'] = explode("\t", $v['targets']);
			if (($v['starttime'] == 0 || $_G['timestamp'] > $v['starttime']) && ($_G['timestamp'] < $v['endtime'] || $v['endtime'] == 0) && in_array(CURSCRIPT, $v['targets'])) {
				if ($v['parameters']['extra']['position'] && $params[2]) {
					if ($params[2] == intval($v['parameters']['extra']['position'])) {
						$ads[] = $v;
						$ad_count ++ ;
					}
				} else {
					$ads[] = $v;
					$ad_count ++ ;
				}
			}

			if ($params[0] == "couplebanner" && $v['parameters']['extra']['position'] == 2) {
				$ads_couple[] = $v;
			}
		}

		if ($params[0] == "couplebanner") {
			$adcontent .= "<div id=\"couplebanner_area\" style=\"display:none;\">";
			if ($ads) {
				$adv_show = $ads[rand(0, $ad_count - 1)];
				$adcontent .= '<div'.($params[1] != '' ? ' class="'.$params[1].'"' : '').'>' . $adv_show['code'] . $ad_close . '</div>';
				if ($adv_show['parameters']['extra']['coupleadid']) {
					foreach ($ads_couple as $_ad){
						if ($_ad[advid] == $adv_show['parameters']['extra']['coupleadid']) {
							$adv_show_2 = $_ad;
						}
					}
					!$adv_show_2 && $adv_show_2 = $ads_couple[rand(0, count($ads_couple) - 1)];
					$adv_show_2 && $adcontent .= '<div'.($params[1] != '' ? ' class="ad_fr ad_cb"' : '').'>' . $adv_show_2['code'] . $ad_close . '</div>';
				}

			} elseif ($ads_couple) {
				$adcontent .= '<div'.($params[1] != '' ? ' class="ad_fr ad_cb"' : '').'>' . $ads_couple[rand(0, count($ads_couple) - 1)]['code'] . $ad_close . '</div>';

			}
			$adcontent .= '</div><script>if (window.screen.availWidth >= 1024) $("#couplebanner_area").show();</script>';
		} else {
			if ($ads) {
				$adcontent = '<div'.($params[1] != '' ? ' class="'.$params[1].'"' : '').'>' . $ads[rand(0, $ad_count - 1)]['code'] . $ad_close . '</div>';
			}
		}
	}

	return $adcontent;
}

function checkholddomain($domain) {
	global $_G;

	$domain = strtolower($domain);
	if(preg_match("/^[^a-z]/i", $domain)) return true;
	$holdmainarr = empty($_G['setting']['holddomain']) ? array('www') : explode('|', $_G['setting']['holddomain']);
	$ishold = false;
	foreach ($holdmainarr as $value) {
		if(strpos($value, '*') === false) {
			if(strtolower($value) == $domain) {
				$ishold = true;
				break;
			}
		} else {
			$value = str_replace('*', '.*?', $value);
			if(@preg_match("/$value/i", $domain)) {
				$ishold = true;
				break;
			}
		}
	}
	return $ishold;
}

function freshcookie($action,$shopid) {
	global $_G, $_SC;

	$shopid = $action.$shopid;
	$isupdate = 1;
	$old = empty($_G['cookie']['supe_refresh_items'])?0:trim($_G['cookie']['supe_refresh_items']);
	$shopidarr = explode('_', $old);
	if(in_array($shopid, $shopidarr)) {
		$isupdate = 0;
	} else {
		$shopidarr[] = trim($shopid);
		ssetcookie('supe_refresh_items', implode('_', $shopidarr));
	}
	if(empty($_G['cookie']['supe_refresh_items'])) $isupdate = 0;

	return $isupdate;
}

function updateviewnum($action,$shopid) {
	global $_G, $_SGLOBAL;

	DB::query('UPDATE '.DB::table($action.'items').' SET viewnum=viewnum+1 WHERE itemid=\''.$shopid.'\'');
}

/**
 * 显示错误信息
 *
 * @param $errorInfo 错误信息
 */
function display_errors($errorInfo) {
	global $_G;
	is_array($_G['ajax_errors']) && showmessage($errorInfo, '', '', '', $_G['ajax_errors']);
}

function dir_clear($dir, $attach = false) {
	$directory = $attach ? dir(A_DIR.'/'.$dir) : dir(B_ROOT.'./'.$dir);
	$dir = $directory->path;
	if(is_dir($dir)) {
		while($entry = $directory->read()) {
			$filename = $dir.'/'.$entry;
			if(is_file($filename)) {
				@unlink($filename);
			}
		}
		$directory->close();
		@touch($dir.'/index.htm');
	}
}

function secho($array, $eixt=1) {
	if(is_array($array)) {
		echo '<pre>';
		print_r($array);
		echo '</pre>';
	} else {
		echo '<br>';
		echo shtmlspecialchars($array);
		echo '<br>';
	}
	if($eixt) exit();
}

?>
